import React, { useMemo, useState } from 'react';
import { useLocation, useHistory, useModel } from 'umi';
import { Button, Form, Input, message, Upload, InputNumber } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { modalApi } from '@/utils/modalReq';
import {
  saveOperatingGuide,
  updataOperatingGuide,
} from '@/service/personal/operatingGuide';

import Editor from './component/slate';

const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt50M = file.size / 1024 / 1024 < 50;
  if (!isLt50M) {
    message.error('Image must smaller than 50MB!');
  }
  return isJpgOrPng && isLt50M;
};

export default function Editors() {
  const { initialState } = useModel('@@initialState');
  const { fileName } = initialState || {};
  const location: any = useLocation();
  const history: any = useHistory();

  const onFinish = async (value: any) => {
    const values = value;
    values.giftKey = values.upData.fileList[0].response.data.giftKey;
    values.content = JSON.stringify(values.content);
    delete values.upData;
    delete values.username;
    if (location?.query?.id) {
      values.id = location?.query?.id;
      const res = await updataOperatingGuide(values);
      if (res?.code === 0) {
        message.success('保存成功');
        history.push({ pathname: '/systemSetup/documentLists' });
      } else {
        message.error('保存失败');
      }
    } else {
      const res = await saveOperatingGuide(values);
      if (res?.code === 0) {
        message.success('保存成功');
        history.push({ pathname: '/systemSetup/documentLists' });
      } else {
        message.error('保存失败');
      }
    }
  };

  const onFinishFailed = () => {
  };

  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const initialValues = useMemo(() => {
    if (location?.query?.id) {
      const newInitialValues = { ...location?.state, ...{ username: '张三' } };
      newInitialValues.upData = {
        fileList: [
          {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: '',
            response: { data: { giftKey: newInitialValues?.giftKey } },
          },
        ],
      };
      newInitialValues.content = JSON.parse(newInitialValues.content);
      return newInitialValues;
    }
    return { username: '张三' };
  }, [location?.state]);

  const disabled = true;

  return (
    <div>
      <div>editor</div>
      <Form
        name="basic"
        style={{ width: '800px', margin: '0 auto' }}
        // labelCol={{ span: 8 }}
        // wrapperCol={{ span: 16 }}
        initialValues={initialValues}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="文档标题"
          name="title"
          rules={[{ required: true, message: 'Please input your title!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="文档内容"
          name="content"
          rules={[{ required: true, message: 'Please input your docment!' }]}
        >
          <Editor />
        </Form.Item>

        <Form.Item
          label="图片上传"
          name="upData"
          rules={[{ required: true, message: 'Please input your upData!' }]}
          help={
            <div>
              <p>附件说明：附件最大支持50M，</p>
              <p>支持格式：JPG、PNG</p>
            </div>
          }
        >
          <Upload
            name={fileName}
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            maxCount={1}
            data={{
              modelName: 'WOED',
              targetAttr: '0',
            }}
            // fileList={{}}
            action={`${modalApi.common}/shopec-systembase/baseattachment/uploadFiles`}
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {imageUrl ? (
              <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>

        <Form.Item
          label="文档排序"
          name="sort"
          rules={[{ required: true, message: 'Please input your sort!' }]}
        >
          <InputNumber />
        </Form.Item>

        <Form.Item
          label="操作账号"
          name="username"
          rules={[{ required: true, message: 'Please input your userName!' }]}
        >
          <Input disabled={disabled} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 8 }}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>

          <Button
            style={{ marginLeft: '15px' }}
            onClick={() =>
              history.push({ pathname: '/systemSetup/documentLists' })
            }
          >
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
